
import { localStorage } from 'common/storage'
import { errorHandle } from './errorHandle'
import { message } from 'common/message'
import Qs from 'qs'
import store from 'store'
axios.defaults.baseURL = '/api'
axios.defaults.headers['User-Type'] = 'KH'
axios.defaults.headers['Authorization'] = 'Basic d2ViOndlYl9rdW5oZW5n'
// 去除-1换成null
function getStr(str) {
  const re = /:(-1)(\D{1})/g
  let tempR
  while ((tempR = re.exec(str))) {
    str = str.replace(tempR[1] + tempR[2], 'null' + tempR[2])
  }
  return str
}

// axios.defaults.headers['blade-auth'] = store.getters['common/token']
export default function fetch(options) {
  axios.defaults.headers['blade-auth'] = store.getters.token
  if (options.isFormData) {
    options.transformRequest = [
      function(data) {
        return Qs.stringify(data, {
          allowDots: true,
          skipNulls: true
        })
      }
    ]
  }

  return new Promise((resolve, reject) => {
    // 创建一个axios实例
    const instance = axios.create({
      timeout: 100000
    })
    /**
     * 请求拦截器
     * 每次请求前，如果存在token则在请求头中携带token
     */
    instance.interceptors.request.use(
      config => {
        if (options.isFormData) {
          config.headers['Content-Type'] =
            'application/x-www-form-urlencoded;charset=utf-8'
        }
        return config
      },
      error => Promise.error(error)
    )
    // 请求处理
    instance(options)
      .then(res => {
        if (options.responseType) {
          resolve(res.data)
          return false
        }
        const {
          data: { data, code, msg, success }
        } = res
        // 请求成功时,根据业务判断状态
        if (code === 200) {
          resolve({
            data: JSON.parse(getStr(JSON.stringify(data))),
            code,
            msg,
            success
          })
          return false
        }
        message.error(msg)
        reject({
          data,
          code,
          msg,
          success
        })
      })
      .catch(error => {
        // 请求失败时,根据业务判断状态
        if (error.response) {
          const resCode = error.response.data.code || error.response.status
          const resMsg = error.response.data.msg || error.response.statusText
          if (resCode === 50004) {
            resolve({
              data: error.response.data.data,
              code: error.response.data.code,
              msg: error.response.data.msg || error.response.data.message
            })
            return
          }
          if (resCode > 51000) {
            resolve({
              data: error.response.data.data,
              code: error.response.data.code,
              msg: error.response.data.msg || error.response.data.message
            })
            return
          }
          if (resCode === 401) {
            errorHandle(resCode, error.response.data.message)
            store.commit('common/SET_TOKEN', null)
            localStorage.remove('token')
            return
          }
          if (resMsg) {
            errorHandle(resCode, resMsg)
          } else {
            errorHandle(resCode, '网络异常，请稍后重试')
          }
          reject({
            code: resCode,
            msg: resMsg
          })
        }
      })
  })
}
